<template>
    <div id="page-product-list">
        <div class="header-panel">
            <div class="control">

                <div class="operations" style="display: flex;">
                    <!-- <router-link to="/products/new"> -->
                    <div style='margin-right: 8px;' @click='handleAdminTransfer'>
                        <el-button v-if='product_data.admin && product_data.admin.is_admin'>产品管理员迁移 <i class='material-icons'>redo</i></el-button>
                    </div>
                    <div style='margin-right: 8px;' @click='handleERPTransfer'>
                        <el-button v-if='product_data.admin && product_data.admin.is_admin'>产品ERP部门转移 <i class='material-icons'>redo</i></el-button>
                    </div>

                    <div @click='handleNew'>
                        <el-button icon="plus" type="primary" v-if=" username != ga_account ">新增产品</el-button>
                    </div>
                    <!-- </router-link> -->
                </div>

                <div class='op-flexbox' v-on:keyup.enter="handleSearch">
                    <div class='op-box'>
                        <el-popover ref='popmenu' placement="bottom-start" trigger="click">

                            <div class='item' @click='cmdtext="域名"'>
                                <el-radio class="radio" v-model="cmd" label="domain">域名</el-radio>
                            </div>
                            <div class='item' @click='cmdtext="产品名"'>
                                <el-radio class="radio" v-model="cmd" label="title">产品名</el-radio>
                            </div>
                            <div class='item' @click='cmdtext="产品id"'>
                                <el-radio class="radio" v-model="cmd" label="product_id">产品id</el-radio>
                            </div>
                            <div class='item' @click='cmdtext="主题"'>
                                <el-radio class="radio" v-model="cmd" label="theme">主题</el-radio>
                            </div>
                            <div class='item' @click='cmdtext="ERPid"'>
                                <el-radio class="radio" v-model="cmd" label="erp_id">ERPid</el-radio>
                            </div>
                            <div class='item' @click='cmdtext="用户"'>
                                <el-radio class="radio" v-model="cmd" label="aid">用户</el-radio>
                            </div>


                        </el-popover>



                        <div class='select-category'>
                            <span class="el-dropdown-link" v-popover:popmenu>
                                <span ref='category' v-text='cmdtext'></span><i class="el-icon-caret-bottom el-icon--right"></i>
                            </span>




                            <!--
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command='域名|domain'>域名</el-dropdown-item>
                                <el-dropdown-item command='产品名|title'>产品名</el-dropdown-item>
                                <el-dropdown-item command='主题|theme'>主题</el-dropdown-item>
                                <el-dropdown-item command='ERPid|erp_id'>ERPid</el-dropdown-item>
                                <el-dropdown-item command='用户|aid' v-if='is_admin'>用户</el-dropdown-item>
                            </el-dropdown-menu>
                            -->
                        </div>


                        <el-input placeholder="输入关键词" :icon="keyword ? 'close' : 'search'" v-model="keyword" v-on:keyup.enter="handleSearch" :on-icon-click="handleSearchOrClose">
                            <el-select v-model="keyword" class='searchuser' slot="prepend" placeholder="用户" v-if="this.cmd == 'aid'" icon="search" @change='handleSearch'>
                                <el-option v-for='item in product_data.user' :label='item.username' :key='item.uid' :value='item.uid'></el-option>
                            </el-select>
                        </el-input>

                    </div>

                </div>

                <el-row class="op">
                    <el-col>
                        <el-col :span="6"><a href='/product.php?act=downloadexcel' class="op-link">导出域名</a></el-col>
                        <el-col :span="10" class="op-checkbox" :offset="8">
                            <el-checkbox v-model="withDel" @change='handleSearch'>已删除的产品</el-checkbox>
                        </el-col>
                    </el-col>
                </el-row>
            </div>

        </div>

        <div class="container">
            <el-table ref="multipleTable" :data="product_data.goodsList" border tooltip-effect="dark" v-loading='table_loading' element-loading-text="拼命加载中"
                @selection-change="handleSelectionChange" @filter-change='handleFilterChange'>
                <el-table-column label="" width='50'></el-table-column>
                <el-table-column type="selection" class='product-selection' ref='sel'>

                </el-table-column>
                <el-table-column label='产品号' width='70' prop='product_id'>

                </el-table-column>

                <el-table-column label="产品信息" width='240'>
                    <template scope="scope">
                        <el-row>
                            <div class='scope-img-col'><a :href="'http://'+scope.row.domain+'/'+scope.row.identity_tag" class="scope-domain" target="_blank"><img :src='scope.row.thumb'></a></div>
                            <div class='scope-name-col'>
                                <a :href="'http://'+scope.row.domain+'/'+scope.row.identity_tag" class="scope-name" target="_blank">
                                    <el-row class="scope-name">{{ scope.row.title }} </el-row>
                                </a>
                                <el-row><span class='scope-price'>{{ scope.row.price }}</span>&nbsp;<span class="scope-unit">{{ scope.row.currency_code }}</span></el-row>
                            </div>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column label="ERP ID" width='90' prop='erp_number'>
                </el-table-column>
                <el-table-column label="域名" width='150'>
                    <template scope="scope">
                        <a :href="'http://'+scope.row.domain+'/'+scope.row.identity_tag" class="scope-domain" target="_blank">{{ scope.row.domain }}/{{ scope.row.identity_tag }}</a>
                    </template>
                </el-table-column>
                <template v-if="administrator">
                    <el-table-column class-name='filter-caption' label='地区' width='110' prop='zone' :filter-multiple='false' :filters="this.$service('table#tag', this.product_data.goodsList, 'zone')"
                        :filter-method="$service('table#filterTag', 'zone')" filter-placement="bottom"></el-table-column>
                    <el-table-column class-name='filter-caption' label="部门ID" width='110' prop="id_department" :filter-multiple='false' :filters="this.$service('table#tag', this.product_data.goodsList, 'id_department')"
                        :filter-method="$service('table#filterTag', 'id_department')" filter-placement="bottom"></el-table-column>
                    <el-table-column class-name='filter-caption' label="优化师" width='110' prop="ad_member" :filter-multiple='false' :filters="this.$service('table#tag', this.product_data.goodsList, 'ad_member')"
                        :filter-method="$service('table#filterTag', 'ad_member')" filter-placement="bottom"></el-table-column>
                    <el-table-column class-name='filter-caption' label="用户" width='110' prop="user" :filter-multiple='false' :filters="this.$service('table#tag', this.product_data.goodsList, 'user')"
                        :filter-method="$service('table#filterTag', 'user')" filter-placement="bottom"></el-table-column>
                </template>
                <el-table-column label="添加时间" width='90'>
                    <template scope="scope">
                        <el-row class="scope-time">{{ scope.row.add_time | filterDate}}</el-row>
                        <el-row class="scope-time">{{ scope.row.add_time | filterTime}}</el-row>
                    </template>
                </el-table-column>
                <el-table-column class-name='filter-caption' label="主题模板" width='98' :filter-multiple='false' :filters="this.$service('table#tag', this.product_data.goodsList, 'theme')"
                    :filter-method="$service('table#filterTag', 'theme')" :filtered-value='filteredValue' filter-placement="bottom"
                    prop='theme'>
                    <template scope="scope">
                        <el-row class="scope-theme">{{ scope.row.theme }}</el-row>
                        <el-row class="scope-theme">{{ scope.row.themelang }}</el-row>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160">
                    <template scope="scope">
                        <section v-if=' username == ga_account '>
                            <a class="scope-op" href='javascript:void(0)' v-if='scope.row.is_del == "0"' @click='handleEdit(scope.row)'>编辑</a>
                        </section>
                        <section v-else>
                            <a class="scope-op" href='javascript:void(0)' v-if='scope.row.is_del == "0"' @click='handleEdit(scope.row)'>编辑</a>
                            <a class="scope-op" href='javascript:void(0)' v-if='scope.row.is_del == "0"' @click='handleCopy(scope.row)'>复制</a>
                            <a class="scope-op" href='javascript:void(0)' v-if='scope.row.is_del == "0"' @click='handleDelete(scope.row)'>删除</a>
                            <a class="scope-op scope-resume" href='javascript:void(0)' v-if='scope.row.is_del=="1"' @click='handleResume(scope.row)'>恢复</a>
                        </section>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination small layout="prev, pager, next, jumper, slot" :page-size="1" @current-change="handleCurrentChange" :total="product_data.pageCount"
                class='with-button'>
                <el-button class='el-pagination__append'>跳转</el-button>
            </el-pagination>

        </div>

        <el-dialog :visible.sync='product_copying' title='复制产品'>
            <el-form>
                <el-form-item label='请输入域名'><br>
                    <el-input v-model='copy.domain'></el-input>
                </el-form-item>
                <el-form-item label='请输入二级目录'><br>
                    <el-input v-model='copy.identity_tag'></el-input>
                </el-form-item>
                <el-form-item label='请选择产品地区'><br>
                    <el-select v-model='copy.id_zone'>
                        <el-option v-for='item in zones' :key='item.id_zone' :value='item.id_zone' :label='item.title'></el-option>
                    </el-select>
                </el-form-item>
                <el-button type="primary" @click="handleCopyProduct()">保存</el-button>
                <el-button @click='() => product_copying = false'>取消</el-button>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    const selectAdmin = {
        template: `<el-select v-model='rootHub.admin'>
                <el-option v-for='item in rootHub.adminlist' :label='item.username' :key='item.uid' :value='item.uid'></el-option>
            </el-select>`,
        data() {
            return {
                rootHub: Vue.rootHub,
            }
        },
    };


    export default {
        data() {
            return {
                product_data: require('../mock/products.json')
                , multipleSelection: []
                , keyword: ""
                , withDel: false
                , page: 1
                , table_loading: false
                , cmd: "domain"
                , adminlist: ["1", "2", "3"]
                , domain: []
                , product_id: []
                , filters: []
                , tags: {}
                , radio: ""
                , cmdtext: '域名'
                , filteredValue: []
                , copy: {
                    product_id: 0
                    , domain: ""
                    , id_zone: 0
                    , identity_tag: ""
                }
                , zones: []
                , product_copying: false
                , handleFilterChanged: null
                , ga_account: 'googleID'
            }
        }
        , computed: {
            username(){
                return this.$store.state.username
            }
            , administrator(){
                return this.$store.state.administrator
            }
        }
        , created() {
            Vue.component('selectAdmin', selectAdmin);
        }
        , mounted() {
            window.product = this;
            this.get();
            let self = this;

            let fix = setInterval(function () {
                if (!self.$refs.sel) return;
                let div = document.querySelectorAll(`.${self.$refs.sel.columnId} .cell`);
                if (div.length == 0) return;
                [...div].forEach(function (obj) {
                    obj.style.paddingLeft = '0px';
                });
                clearInterval(fix);
            }, 1000);

            this.handleFilterChanged = function (e) {
                let el = e.target;
                if (!el.classList.contains('el-checkbox__original')) return;
                if (el.value == 'Symbol(ALL)' && el.checked) {
                    let group = Vue.element(el.closest(".el-checkbox-group"));
                    console.log(group);

                }

            };
            document.addEventListener('change', this.handleFilterChanged, true);
        }
        , beforeDestroy() {
            if (this.handleFilterChanged) document.removeEventListener('change', this.handleFilterChanged);
        }
        , methods: {
            get() {
                if (this.table_loading) {
                    return;
                }
                this.$service('country#list').then(res => this.zones = res.body);
                this.table_loading = true;
                this.$service('product#list', this.cmd, this.keyword, this.withDel, this.page)
                    .then(res => {
                        setTimeout(_ => this.table_loading = false, 0);  // vue async feature
                        this.product_data = res.body;
                    });
            }
            , handleEdit(val) {
                this.$service('product#edit', val.product_id);
            }
            , handleDelete(val) {
                const h = this.$createElement;
                this.$msgbox({
                    title: '确认删除',
                    message: h('p', null, [
                        h('span', null, '确实要删除掉 '),
                        h('span', null, val.title),
                        h('span', null, ' 吗'),
                    ]),
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(action => {
                    if (action === 'confirm') {
                        this.$service('product#delete', val.product_id).then(res => {
                            if (res.body.ret == '0') {
                                this.$message.error({
                                    message: res.body.msg || '删除失败'
                                })
                            } else {

                                this.$message({
                                    message: res.body.msg || '删除成功'
                                })
                                this.get();
                            }
                        });
                    }
                });

            }, handleResume(val) {
                const h = this.$createElement;
                this.$msgbox({
                    title: '确认恢复',
                    message: h('p', null, [
                        h('span', null, '确实要恢复 '),
                        h('span', null, val.title),
                        h('span', null, ' 吗'),
                    ]),
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(action => {
                    if (action === 'confirm') {
                        this.$service('product#resume', val.product_id).then(res => {
                            if (res.body.ret == '0') {
                                this.$message.error({
                                    message: res.body.msg || '恢复失败'
                                })
                            } else {
                                this.$message({
                                    message: res.body.msg || '恢复成功'
                                })
                                this.get();
                            }
                        });
                    }
                });
            }, handleERPTransfer() {
                const h = this.$createElement;
                this.$prompt("\t", '输入要转移的erp业务组id',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputPlaceholder: '业务组id',
                        inputPattern: /^\d+$/,
                        inputErrorMessage: '部门id必须是数字'
                    }
                ).then(({ value }) => {
                    this.$service('product#transferDomain', this.domain, value).then(res => {
                        if (res.body.ret == '0') {
                            this.$message.error({
                                message: res.body.msg || '域名转移失败'
                            })
                        } else {
                            this.$message({
                                message: res.body.msg || '域名转移成功'
                            })
                            this.get();
                        }
                    });
                });
            }, handleAdminTransfer() {
                const h = this.$createElement;
                Vue.rootHub.adminlist = this.product_data.user;
                Vue.rootHub.admin = this.product_data.user[0].uid;

                let node = h('selectAdmin', null, null);
                this.$msgbox({
                    title: '选择对应管理员转移',
                    message: node,
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(action => {
                    if (action === 'confirm') {
                        this.$service('product#transferDepartment', this.product_id, Vue.rootHub.admin).then(res => {
                            if (res.body.ret == '0') {
                                this.$message.error({
                                    message: res.body.msg || '产品转移失败'
                                })
                            } else {
                                this.$message({
                                    message: res.body.msg || '产品转移成功'
                                })
                                this.get();
                            }
                        });
                    }

                });
            }, handleNew() {
                this.$service('product#new');
            }, handleSearch() {
                if (!this.table_loading) {
                    this.get();
                } else {
                    this.$message({ message: "正在拼命加载中，请稍候" })
                }
            }, handleCurrentChange(val) {
                this.page = val;
                this.get();
            }, handleSelectionChange(val) {
                this.domain = val.map(x => x.domain);
                this.product_id = val.map(x => x.product_id);
            }, handleClose() {
                this.keyword = '';
                this.handleSearch();
            }, handleSearchOrClose() {
                this.keyword ? this.handleClose() : this.handleSearch();
            }, handleCopy(row) {
                this.product_copying = true;
                this.copy = {
                    domain: row.domain
                    , product_id: row.product_id
                    , id_zone: this.zones[0].id_zone
                };
                this.product_copying = true;
            }, handleCopyProduct() {
                console.log(this.copy)
                this.$service('product#copy', this.copy).submitMessage().then(res => {
                    if (res.body.ret == 1) {
                        this.get();
                        this.product_copying = false;
                    }
                });
            }, handleFilterChange(...args) {
                console.log(args);
            }
        }
        , filters: {
            filterTime: function (val) {
                return Vue.service('|>time', val);
            },
            filterDate: function (val) {
                return Vue.service('|>date', val);
            }
        }
    }

</script>